#include "mode_defrost.h"
#include "main_motor.h"
#include "actuator_control.h"
#include "timer_utils.h"

// 解冻模式内部状态
static struct {
    uint32_t motor_timer;
    bool motor_on;
} s_defrost_state;

// 解冻模式进入
void defrost_mode_enter(ModeConfig* config) {
    memset(&s_defrost_state, 0, sizeof(s_defrost_state));
    
    // 初始化电机配置
    MotorConfig motor_cfg = {
        .min_current = 100,    // 解冻时电流阈值放宽
        .max_current = 1000,
        .start_timeout = 5000,
        .retry_count = 3,
        .protection_time = 30000
    };
    motor_init(&motor_cfg);
    
    // 开启制热（旁通阀打开）
    actuator_set_bypass_valve(true);
    
    s_defrost_state.motor_timer = get_system_time_ms();
    s_defrost_state.motor_on = false;
    
    printf("Entering defrost mode\n");
}

// 解冻模式处理
void defrost_mode_process(ModeConfig* config, SensorData* sensors, DeviceState* state) {
    uint32_t current_time = get_system_time_ms();
    
    // 处理电机状态
    motor_process(sensors->motor_current);
    state->motor_running = (motor_get_state() == MOTOR_STATE_RUNNING);
    
    // 检查电机错误
    if (motor_get_error() == MOTOR_ERROR_START_FAILED) {
        state->in_error = true;
        state->error_code = ERROR_MOTOR_CURRENT;
        return;
    }
    
    // 超时检查
    if (state->mode_runtime >= config->defrost_timeout) {
        state->in_error = true;
        state->error_code = ERROR_DEFROST_TIMEOUT;
        return;
    }
    
    // 温度控制
    if (sensors->cabinet_temp < config->defrost_target - 1.0f) {
        // 开启压缩机加热
        if (!state->comp_running) {
            actuator_set_compressor(true);
            state->comp_running = true;
        }
    } else if (sensors->cabinet_temp >= config->defrost_target) {
        // 解冻完成
        actuator_set_compressor(false);
        actuator_set_bypass_valve(false);
        motor_stop();
        state->comp_running = false;
        state->bypass_valve = false;
        state->motor_running = false;
        return;
    }
    
    // 电机间歇运行（30秒开，30秒关）
    if (current_time - s_defrost_state.motor_timer > 30000) {
        s_defrost_state.motor_timer = current_time;
        s_defrost_state.motor_on = !s_defrost_state.motor_on;
        
        if (s_defrost_state.motor_on) {
            if (motor_get_state() == MOTOR_STATE_STOPPED) {
                motor_start();
            }
        } else {
            motor_stop();
        }
    }
    
    state->bypass_valve = true;  // 保持旁通阀打开（制热模式）
}

// 解冻模式退出
void defrost_mode_exit(void) {
    motor_stop();
    actuator_set_compressor(false);
    actuator_set_bypass_valve(false);
    
    printf("Exiting defrost mode\n");
}
